package com.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.common.entity.GlobalMsg;
import com.common.entity.Order;
import com.common.entity.Rsp;
import com.mq.conf.DelayQueueConfig;
import com.mq.feign.OrderFeign;
import com.mq.feign.UserFeign;
import com.rabbitmq.client.Channel;
//import com.wn.mapper.OrderMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@Component
public class DelayedConsumer {

    @Resource
    private OrderFeign orderFeign;
    @Resource
    private UserFeign userFeign;

   //延时队列
    @RabbitListener(queuesToDeclare = @Queue(DelayQueueConfig.PROCESS_QUEUE))
    public void listen(String msg, Channel channel, Message message) throws IOException {
        try {
            System.out.println("订单超时 业务处理"+msg);
            //改变订单状态,2--------超时
            Order order = new Order();
            order.setOrderNo(msg);
            order.setStatus(2);
            order.setOnlyCode("1");
            orderFeign.updateOrderStatus(order);

//            Map<String,Object> map = (Map<String, Object>) JSON.parse(msg);
//            GlobalMsg globalMsg = new GlobalMsg();
//            globalMsg.setMsgId(UUID.randomUUID().toString().replaceAll("-",""));
//            globalMsg.setUserId((String) map.get("userId"));
//            globalMsg.setMsgBody((String) map.get("msgBody"));
//            globalMsg.setMsgType((String) map.get("msgType"));
//            globalMsg.setDeleted(0);
//            globalMsg.setMsgStatus(0);
//            Rsp rsp = userFeign.addOneMsg(globalMsg);

            //手动确认消息消费成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            System.out.println("订单业务超时处理异常");

            //手动确认消息消费失败  并且让消息重回队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }finally {
        }
    }
}
